<!--
-- Author:  Robert Derveloy
-- Written: 2012-12-01
-- 
-- Copyright (c) 2012-2015 -  Robert Derveloy
-- 
-- This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
-- To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/4.0/.
--
-->
<html>
	<head>
		<title>JavaScript Sound Recorder Demo</title>		
	</head>
	<body>
		<div id="div_RecordingNotSupported" name="div_RecordingNotSupported" style="display:block;">
			Sorry, it appears that your browser does not support getUserMedia audio recording.  Please see the <a href="http://caniuse.com/#feat=stream">Can I Use website</a> for a list of capable browsers.
		</div>
		<form id="form_controls" name="form_controls">
			<button id="button_startRecording" onclick="handleStartRecordingButtonClick();" type="button" style="display:none;">Start Recording</button>
			<button id="button_stopRecording" onclick="handleStopRecordingButtonClick();" type="button" style="display:none;">Stop Recording</button>
		</form>
        <br/>
        <br/>
        <footer>
            <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-nc-sa/4.0/80x15.png" /></a>
            <br />
            <span xmlns:dct="http://purl.org/dc/terms/" property="dct:title">
                Javascript Sound Recorder
            </span>
            by
            <a xmlns:cc="http://creativecommons.org/ns#" href="https://github.com/rderveloy/JavaScript-Sound-Recorder/" property="cc:attributionName" rel="cc:attributionURL">
                Robert Derveloy
            </a>
            is licensed under a
            <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/">
                Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License
            </a>.
        </footer>
		<script src='SoundRecorder.js'></script>
		<script>
			// variables
			var wavFileBlob = null;
			var recorderObj = null;
			var scriptProcessor = null;										
			var detectGetUserMedia = new BrowserGetUserMediaDetection();

			
			//First, check to see if get user media is supported:
			console.log("Get user media supported: " + detectGetUserMedia.getUserMediaSupported());
															
			if(detectGetUserMedia.getUserMediaSupported())
			{   
				console.log("Get user media is supported!");
				console.log("Supported get user media method: " + detectGetUserMedia.getUserMediaMethod());
				
				console.log("Assigning get user media method.");
				navigator.getUserMedia = detectGetUserMedia.getUserMediaMethod();
				
				console.log("Requesting microphone access from browser.");
				navigator.getUserMedia({audio:true}, success, failure);
				
				document.getElementById("div_RecordingNotSupported").style.display="none"; // hide recording not supported message
				document.getElementById("button_startRecording").style.display="block"; // show start recording button
					
			}
			else
			{
				console.log("ERROR: getUserMedia not supported by browser.");
								
				alert('Your browser does not appear to support audio recording.');
			}
			
			
			//Get user media failure callback function:
			function failure(e)
			{
				console.log("getUserMedia->failure(): ERROR: Microphone access request failed!");												    												    
				
				var errorMessageToDisplay;
				var PERMISSION_DENIED_ERROR = "PermissionDeniedError";
				var DEVICES_NOT_FOUND_ERROR = "DevicesNotFoundError"; 
				
				console.log(e);
				console.log(e.name);
			   
				switch(e.name)
				{
					case PERMISSION_DENIED_ERROR:
						errorMessageToDisplay = 'ERROR: You must grant permission before audio recording can continue.';
						break;
					case DEVICES_NOT_FOUND_ERROR:
						errorMessageToDisplay = 'ERROR: No microphones detected.  Please connect and configure your microphone.';
						break;
					default:
						errorMessageToDisplay = 'ERROR: The following unexpected error occurred while attempting to connect to your microphone: '+e.name;
						break;                
				}
				console.log("getUserMedia->failure(): "+errorMessageToDisplay);
				alert(errorMessageToDisplay); 
			}
			
			//Get user media success callback function:
			function success(e)
			{
				console.log("getUserMedia->success(): Microphone access request was successful!");
				
				var BUFFER_SIZE = 2048;
				var RECORDING_MODE = PredefinedRecordingModes.MONO_5_KHZ;												   												    
				var SAMPLE_RATE = RECORDING_MODE.getSampleRate();
				var OUTPUT_CHANNEL_COUNT = RECORDING_MODE.getChannelCount();
				
				
				console.log("getUserMedia->success(): Detecting window audio context.");
				var detectWindowAudioContext = new BrowserWindowAudioContextDetection();
				
				if(detectWindowAudioContext.windowAudioContextSupported())
				{
					console.log("getUserMedia->success(): Window audio context supported.");
					
					var windowAudioContext = detectWindowAudioContext.getWindowAudioContextMethod();
					
					console.log("getUserMedia->success(): Window audio context method: " + windowAudioContext);
				
					console.log('getUserMedia->success(): Creating recorder object.');
					
					recorderObj = new SoundRecorder(windowAudioContext, BUFFER_SIZE, SAMPLE_RATE, OUTPUT_CHANNEL_COUNT);
					
					console.log('getUserMedia->success(): Initializing recorder object.');
					recorderObj.init(e);
			
					console.log('getUserMedia->success(): Assigning onaudioprocess event function.');
				
					recorderObj.recorder.onaudioprocess = function(e)
					{            
						//Do nothing if not recording:
						if (!recorderObj.isRecording()) return;                        
						// Copy the data from the input buffers;
						var left = e.inputBuffer.getChannelData (0);
						var right = e.inputBuffer.getChannelData (1);
						recorderObj.cloneChannelData(left, right);            
						console.log('SoundRecorder.recorder.onaudioprocess: Saving audio data...');
					};
					
					console.log('getUserMedia->success(): Recorder object successfully created and initialized.');
					console.log('getUserMedia->success(): Recorder object ready status: ' + recorderObj.isReady());
					
					document.getElementById("button_startRecording").disabled = false;
					document.getElementById("button_stopRecording").disabled = true;
				}
				else
				{
					var messageString = "Unable to detect window audio context, cannot continue.";
					console.log("getUserMedia->success(): "+ messageString);
					alert(messageString);
					return;
				}    
			}
						
			function handleStartRecordingButtonClick()
			{
				//Update UI:
				document.getElementById("button_startRecording").disabled = true;
				document.getElementById("button_startRecording").style.display = "none";
				document.getElementById("button_stopRecording").style.display = "block";
				document.getElementById("button_stopRecording").disabled = false;
				
				//Start the recording:
				console.log("Starting new recording...");
				recorderObj.startRecordingNewWavFile();
				
			}
			
			function handleStopRecordingButtonClick()
			{
				//Disable stop button to prevent clicking too many times:
				document.getElementById("button_stopRecording").disabled = true;
				document.getElementById("button_stopRecording").style.display = "none";
				
				//Stop the recording:
				console.log("Stopping recording.");
				recorderObj.stopRecording();
				
				//Save the recording by building the wav file blob and send it to the client:
				console.log("Building wav file.");
				wavFileBlob = recorderObj.buildWavFileBlob();
				
				console.log("Downloading...");
				wavFileBlob.downloadLocally();

				//Re-enable the start button after saving:
				document.getElementById("button_startRecording").disabled = false;
				document.getElementById("button_startRecording").style.display = "block";
			}
		</script>

	</body>
</html>
